package vip.xiaonuo.bi.core.datasource.common.manager;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import vip.xiaonuo.bi.core.datasource.common.client.Client;
import vip.xiaonuo.bi.core.datasource.common.client.DataSourceClient;
import vip.xiaonuo.bi.core.datasource.common.client.HttpOrApiClient;

import java.util.Map;


/**
 * 数据库默认对象实例管理
 * @author 顾育司
 * @date  2023/12/15 12:09
 */
@Component
public class ClientManager implements InitializingBean, ApplicationContextAware {


    Table<Class<?> ,String , Client> clientInstant = HashBasedTable.create();

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() {
        Map<String, DataSourceClient> beanMap = applicationContext.getBeansOfType(DataSourceClient.class);
        //遍历该接口的所有实现，将其放入map中
        for (Client serviceImpl : beanMap.values()) {
            clientInstant.put(DataSourceClient.class,serviceImpl.getType(), serviceImpl);
            System.out.println("类型："+serviceImpl);
        }

        Map<String, HttpOrApiClient> beanMap1 = applicationContext.getBeansOfType(HttpOrApiClient.class);
        //遍历该接口的所有实现，将其放入map中
        for (Client serviceImpl : beanMap.values()) {
            clientInstant.put(HttpOrApiClient.class,serviceImpl.getType(), serviceImpl);
            System.out.println("类型："+serviceImpl);
        }
    }

    /**
     * 获取对应的数据库【处理实例对象】 注意：并非是数据库连接实例对象
     * @param type
     * @return
     */
    public  <T extends DataSourceClient> T getClient(String type) {
        return (T) this.clientInstant.get(DataSourceClient.class,type);
    }

    public  <T extends HttpOrApiClient> T getHttpClient(String type) {
        return (T) this.clientInstant.get(HttpOrApiClient.class,type);
    }
}

